import { Device, GatewayType } from "@/api/interface/iot";
import { SchemaItem } from "@/components/JsonSchemaForm/interface";
import { RouterPath } from "@/enums/routerPath";
import { DeviceType } from "@/enums/statusEnum";
import { AuthBtns, SchemaNodeKey, SchemaNodeType } from "@/utils/constants";
import { gotoPage } from "@/utils/routerUtil";
import { parseProfileFromRuntime, parseProfileFromSystem, parseSchemaFromBasic } from "@/utils/schema";
import { PropType } from "vue";
import OnlineStatus from "../../Status/OnlineStatus";
import DialogBox from "@/components/DialogBox";
import BaseMap from "@/components/Map/antvl7/BaseMap";
import { getProduct } from "@/api/modules/iot/product";
const otherPages: { [key: string]: any } = {
	gatewaySn: { field: "gatewaySn", path: RouterPath.gatewayDetail },
	productModel: { field: "productModel", path: RouterPath.productDetail, param: { menuId: AuthBtns.iotProduct } }
};
/**
 * 基本信息：scheme中的的basic内容
 */
//根据Schema绘制基本信息
export default defineComponent({
	props: {
		type: {
			type: String,
			default() {
				return GatewayType.Device;
			}
		}
	},
	emits: ["submit"],
	setup(props, { emit }) {
		const productInfo = ref({});
		let schema: SchemaItem;
		let profile: any;
		if (props.type == GatewayType.Device) {
			schema = inject<any>(SchemaNodeKey.schema);
			profile = inject<any>(SchemaNodeKey.profile);
		} else if (props.type == GatewayType.Gateway) {
			schema = inject<any>(SchemaNodeKey.gatewaySchema);
			profile = inject<any>(SchemaNodeKey.gatewayProfile);
		} else {
			schema = { value: {} };
			profile = { value: {} };
		}
		provide("productInfo", productInfo);
		const deviceInfo = inject<any>(SchemaNodeKey.detailInfo);
		if (deviceInfo.detail.productModel) {
			getProduct({
				productModel: deviceInfo.detail.productModel
			}).then(res => {
				productInfo.value = res.result;
			});
		}
		const basic: SchemaItem = parseSchemaFromBasic(schema.value);
		const system: SchemaItem = parseProfileFromSystem(profile.value);
		const runtime: SchemaItem = parseProfileFromRuntime(profile.value);

		const locationDialog = reactive({
			visible: false,
			title: "设备位置信息",
			detail: {} as any
		});
		const showLocation = () => {
			locationDialog.visible = true;
			locationDialog.detail = deviceInfo.detail;
		};
		return () => {
			return (
				<>
					<div class="block-basic p-8">
						{/*位置信息*/}
						<DialogBox
							title={locationDialog.title}
							v-model:visible={locationDialog.visible}
							class="dialog-dense"
							width="85vw"
							onConfirm={() => {
								emit("submit");
								locationDialog.visible = false;
							}}
						>
							{locationDialog.visible ? <BaseMap style="height:50vh" editerMarker detail={locationDialog.detail} /> : null}
							<div class="address-detail">{locationDialog.detail.location?.address}</div>
						</DialogBox>
						{Object.keys(system).length || Object.keys(runtime).length ? (
							<div class="h-10">
								<div class="title-left-line"></div>基本信息
							</div>
						) : null}
						<div class="grid grid-cols-3">
							{/* 根据schema定义，循环属性字段项 */}
							{Object.keys(basic).map(key => {
								return basic[key].hide ? null : (
									<div class="flex item">
										{/* 加载每个属性名称 */}
										<div class="info-title text-right w-1/3">{key == "deptId" ? "所属分组" : basic[key].title}</div>

										{/* 加载每个属性项数据值 */}
										<div class="info-text flex-1 truncate">
											<ItemValue onLocation={showLocation} propScheme={basic[key]} propKey={key} propValue={deviceInfo.detail} />
										</div>
									</div>
								);
							})}
						</div>

						{/* 运行信息 */}
						<OtherInfo dataInfo={runtime} title="系統信息" />

						{/* 系统信息 */}
						<OtherInfo dataInfo={system} title="系統信息" />
					</div>
				</>
			);
		};
	}
});

const OtherInfo = defineComponent({
	props: {
		title: String,
		dataInfo: {
			type: Object as PropType<SchemaItem>,
			default() {
				return {};
			}
		}
	},
	setup(props) {
		const collapsedState = reactive<{ [key: string]: boolean }>({});
		return () => {
			return (
				<>
					{Object.keys(props.dataInfo).length ? (
						<>
							<div class="mt-10"></div>
							<div class="h-10">
								<div class="title-left-line"></div>
								<span>{props.title}</span>
							</div>
							{Object.keys(props.dataInfo).map(group => {
								return (
									<>
										<div class="mb-6 group-item">
											<div class="group-title">
												<el-button
													link
													type="primary"
													onClick={() => (collapsedState[group] = !collapsedState[group])}
													class={`toggle-detail-size iconfont ${collapsedState[group] ? "iconchevrons-down" : "iconchevrons-up"}`}
													title={`${!collapsedState[group] ? "收起" : "展开"}`}
												>
													<span>{group}</span>
												</el-button>
											</div>
											{!collapsedState[group] ? (
												<div class="grid grid-cols-3">
													<ProfileItem propKey={group} propValue={props.dataInfo[group]} />
												</div>
											) : null}
										</div>
									</>
								);
							})}
						</>
					) : null}
				</>
			);
		};
	}
});

const ProfileItem = defineComponent({
	props: {
		propScheme: {
			type: Object,
			default() {
				return {};
			}
		},
		propKey: {
			type: String,
			required: true,
			default: ""
		},
		propValue: {
			type: [Object, String, Number],
			default() {
				return {};
			}
		}
	},
	emits: [],
	setup(props, {}) {
		// console.log(props.propKey, props.propValue);
		return () => {
			return props.propValue && typeof props.propValue == "object" ? (
				<>
					{Array.isArray(props.propValue) ? (
						<el-tabs class="col-span-3" model-value={props.propKey + `[0]`}>
							{props.propValue.map((item, i) => {
								return (
									<el-tab-pane label={props.propKey + `[${i}]`} name={props.propKey + `[${i}]`}>
										<div class="grid grid-cols-3">
											{Object.keys(item).map(ck => {
												return (
													<div class="flex item">
														{/* 加载每个属性名称 */}
														<div class="info-title text-right w-1/3">{ck}</div>

														{/* 加载每个属性项数据值 */}
														<div class="info-text flex-1 truncate">
															{Array.isArray(item[ck]) ? (
																<>
																	{!item[ck].length ? "--" : ""}
																	{item[ck].map((ccv: any) => {
																		return <div>{typeof ccv == "object" ? JSON.stringify(ccv) : ccv || "--"}</div>;
																	})}
																</>
															) : (
																item[ck]
															)}
														</div>
													</div>
												);
											})}
										</div>
									</el-tab-pane>
								);
							})}
						</el-tabs>
					) : (
						<>
							{/* 加载嵌套子项 */}
							{Object.keys(props.propValue).map(key => {
								let info = props.propValue as { [key: string]: any };
								return <ProfileItem propKey={key} propValue={info[key]} />;
							})}
						</>
					)}
				</>
			) : (
				<div class="flex item">
					{/* 加载每个属性名称 */}
					<div class="info-title text-right w-1/3">{props.propKey}</div>

					{/* 加载每个属性项数据值 */}
					<div class="info-text flex-1 truncate">{props.propValue}</div>
				</div>
			);
		};
	}
});

const ItemValue = defineComponent({
	props: {
		propScheme: {
			type: Object,
			default() {
				return {};
			}
		},
		propKey: {
			type: String,
			required: true,
			default: ""
		},
		propValue: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	emits: ["location"],
	setup(props, { emit }) {
		const product = ref<Device.ResProduct | any>({});
		const clickLink = (param: { key: string; value: any }, path: RouterPath) => {
			if (param.key == "productModel") {
				let gotoParam = { ...otherPages.productModel.param };
				gotoParam[param.key] = param.value;
				gotoPage(path, gotoParam);
			} else {
				gotoPage(path, param);
			}
		};

		if (props.propKey == "productModel") {
			const productInfo = inject<any>("productInfo");
			watchEffect(() => {
				product.value = productInfo.value;
			});
		}
		return () => {
			return (
				<span>
					{props.propScheme.type == SchemaNodeType.object ? (
						<span>
							{/* 特殊处理 */}
							{props.propKey == "location" ? (
								<el-tooltip show-after={500} content={props.propValue[props.propKey]?.address || "--"}>
									<span class="cursor-pointer el-text--primary" onClick={() => emit("location")}>
										{props.propValue[props.propKey]?.address || "--"}
									</span>
								</el-tooltip>
							) : (
								<>
									{/* 循环子属性 */}
									{Object.keys(props.propScheme[SchemaNodeKey.properties]).map((subKey, i) => {
										return (
											<>
												{i > 0 ? <span class="pr-1">, </span> : null}
												<span>{props.propScheme[SchemaNodeKey.properties]![subKey]?.title}</span>
												<span>{props.propValue[props.propKey] ? props.propValue[props.propKey][subKey] : null}</span>
											</>
										);
									})}
								</>
							)}
						</span>
					) : (
						<span>
							{/* 根据配置的详情字段，跳到其他页面 */}
							{Object.keys(otherPages).includes(props.propKey) ? (
								<>
									{/* 字段没有内容不支持跳转 */}
									{!props.propValue[props.propKey] ? (
										"--"
									) : (
										<el-link
											type="primary"
											onClick={() =>
												clickLink({ key: props.propKey, value: props.propValue[props.propKey] }, otherPages[props.propKey].path)
											}
										>
											{props.propKey == "productModel"
												? product.value?.name || props.propValue[props.propKey]
												: props.propValue[props.propKey]}
										</el-link>
									)}
								</>
							) : (
								<>
									{/* 无需调整页面的字段 */}
									{/* 数据为json对象时，页面会解析报错 */}
									{props.propKey == "onlineStatus" ? (
										<OnlineStatus v-model={props.propValue[props.propKey]} />
									) : props.propKey == "deptId" ? (
										props.propValue["deptName"]
									) : props.propKey == "type" ? (
										DeviceType[props.propValue[props.propKey]]
									) : props.propValue[props.propKey] && typeof props.propValue[props.propKey] == SchemaNodeType.object ? (
										JSON.stringify(props.propValue[props.propKey])
									) : (
										props.propValue[props.propKey] || "--"
									)}
								</>
							)}
						</span>
					)}
				</span>
			);
		};
	}
});
